package com.wlyuan.open.domain.client.respository;

import com.wlyuan.core.exception.AssertUtils;
import com.wlyuan.open.core.exception.OpenClientError;
import com.wlyuan.open.remote.facade.UserFacade;
import com.wlyuan.open.utils.OpenClientDetailBuilder;
import com.wlyuan.open.vo.OpenClientDetailVO;
import com.wlyuan.redisson.repository.BaseCacheResolver;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author lijing
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OpenClientCacheResolver implements BaseCacheResolver<String, OpenClientDetailVO> {
    private final OpenClientRepository openClientRepository;
    private final UserFacade userFacade;

    @Override
    public OpenClientDetailVO resolve(String appId) {
        var application = openClientRepository.ofAppId(appId);
        return Optional.ofNullable(application.getUserId()).map(u -> {
            var user = userFacade.getById(u.getId());
            AssertUtils.assertNotNull(user, new OpenClientError("应用账号不存在"), application);
            return new OpenClientDetailBuilder(application).withClient(application).withUser(user).build();
        }).orElse(new OpenClientDetailBuilder(application).withClient(application).build());
    }
}
